var express = require('express');
var router = express.Router();
var User = require('../models/user.js');

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

router.get('/login', function(req, res, next) {
  res.render('login', { title: 'User Login'});
});

router.post('/login', function(req, res, next) {
  var uname = req.body.uname;
  User.findOne({name: uname}, function(err, doc) {
    if (err) {
      res.send(500);
      console.error(err);
    } else if (!doc) {
      req.session.error = 'user is not found.';
      res.send(404);
    } else {
      if (req.body.upwd !== doc.password) {
        req.session.error = 'password is wrong.';
        res.send(404);
      } else {
        req.session.user = doc;
        res.send(200);
      }
    }
  });
});

router.get('/register', function(req, res, next) {
  res.render('register', { title: 'User Register'});
});

router.post('/register', function(req, res, next) {
  var uname = req.body.uname;
  var upwd = req.body.upwd;
  User.findOne({name: uname}, function(err, doc) {
    if (err) {
      res.send(500);
      req.session.error = 'net error.';
      console.error(err);
    } else if (doc) {
      req.session.error = 'username is exist.';
      res.send(500);
    } else {
      User.create({
        name: uname,
        password: upwd
      }, function(err, doc) {
        if (err) {
          res.send(500);
          console.error(err);
        } else {
          req.session.error = 'create successful.';
          res.send(200);
        }
      });
    }
  });
});

router.get('/home', function(req, res) {
  if (!req.session.user) {
    req.session.error = '用户没登录';
    res.redirect("/login");
  }
  console.log(req.session.user);
  res.render('home', {title: 'Home'});
});

router.get('/logout', function(req, res) {
  req.session.user = null;
  req.session.error = null;
  res.redirect('/');
});

module.exports = router;
